package pl.easyshop.core.services.user;

import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import pl.easyshop.core.model.UserGroupModel;
import pl.easyshop.core.model.UserModel;
import pl.easyshop.core.services.AbstractBaseService;

/**
 * Default implementation of interface {@link UserService}.
 * 
 * @author Pawel Witkowski
 */
@Service("userService")
public class UserServiceImpl extends AbstractBaseService implements UserService {

	/** Logger. */
	private final static Logger LOG = Logger.getLogger(UserServiceImpl.class);
	
	@Override
	@Transactional(readOnly=true)
	public boolean checkAvaiableUsername(String username) {
		LOG.info("Invokde checkAvaiableUsername");
		UserModel model = getDAORegistry().getUserDAO().findByUserName(username);
		LOG.debug("Found user:" + model);
		return model==null;
	}

	@Override
	@Transactional
	public UserData registrationUser(UserData data) {
		LOG.info("Invokde registrationUser");
		LOG.debug("User data: " + data);
		UserModel model = getDozerMapper().map(data, UserModel.class);
		model.setCreateDate(new Date());
		LOG.debug("New user data: " + model);
		Long userId = getDAORegistry().getUserDAO().save(model);
		model = getDAORegistry().getUserDAO().findById(userId);
		UserData userData = null;
		if(model != null) {
			userData = getDozerMapper().map(model, UserData.class);
		} 
		return userData;
	}

	@Override
	@Transactional
	public void updateUser(UserData data) {
		// TODO Auto-generated method stub
		
	}

	@Override
	@Transactional
	public void deleteUser(Long id) {
		LOG.info("Invokde deleteUser");
		LOG.debug("Id: " + id);
		getDAORegistry().getUserDAO().delete(id);
	}

	@Override
	@Transactional(readOnly=true)
	public UserData loadUserData(Long id) {
		LOG.info("Invokde loadUserData");
		LOG.debug("Id: " + id);
		UserModel model = getDAORegistry().getUserDAO().findById(id);
		UserData userData = null;
		if(model != null) {
			userData = getDozerMapper().map(model, UserData.class);
		} 
		return userData;
	}

	@Override
	@Transactional(readOnly=true)
	public UserData loadByUsername(String username) {
		LOG.info("Invokde loadByUsername");
		LOG.debug("Username: " + username);
		UserModel model = getDAORegistry().getUserDAO().findByUserName(username);
		UserData userData = null;
		if(model != null) {
			userData = getDozerMapper().map(model, UserData.class);
		} 
		return userData;
	}

	@Override
	@Transactional(readOnly=true)
	public List<UserData> getAllUsers() {
		// TODO Auto-generated method stub
		return null;
	}

}
